﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Principal;

namespace Viettel.VOFFICE.Web.Helpers
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
            string actionName = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
            //string[] roles = System.Web.Security.Roles.GetRolesForUser();
            var unitOfwork = new Viettel.VOFFICE.DAO.DAL.UnitOfWork();
            Users = unitOfwork.RoleRepository.GetUserByControllerActionName(controllerName, actionName);
            return base.AuthorizeCore(httpContext);
        }

        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            //start.chỉ để test
            //HandleUnauthorizedRequest(filterContext);
            //return;
            //end.chỉ để test
            var cookieName = FormsAuthentication.FormsCookieName;
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
                filterContext.HttpContext.Request.Cookies == null ||
                filterContext.HttpContext.Request.Cookies[cookieName] == null)
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }

            var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket != null)
            {
                var roles = authTicket.UserData.Split(',');
                var userIdentity = new GenericIdentity(authTicket.Name);
                var userPrincipal = new GenericPrincipal(userIdentity, roles);

                filterContext.HttpContext.User = userPrincipal;
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }

            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new Http403Result();
            }
            else
                base.HandleUnauthorizedRequest(filterContext);
        }

        /// <summary>
        /// Trả về statuscode 403 nếu request không authen được
        /// </summary>
        private class Http403Result : ActionResult
        {
            public override void ExecuteResult(ControllerContext context)
            {
                context.HttpContext.Response.StatusCode = 403;
                context.HttpContext.Response.Write(Resources.Resources.UnAuthorized);
            }
        }
    }
}